package Test;

public class Test1 {
    public static void testException(int n){
        if(n == 0){
            throw new ArithmeticException("产生异常了");
        }
    }
    public static int getindex(int[] array,int index){
        if(array == null){
            throw new NullPointerException("传递的数组为空");
        }
        if(index>=array.length||index<0){
            throw new ArrayIndexOutOfBoundsException("转递的下标越界了");
        }
        return array[index];
    }



    public static void main6(String[] args) {
        try{
            int[] arr = {1,2,3};
            arr[100] = 10;
            arr[0] = 10;
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }finally {
            System.out.println("finally中的代码一定会执行");
        }
        System.out.println("如果没有抛出异常，或者异常被处理了，try-catch后的代码也会执行");
    }

    public static void main5(String[] args) {
        int[] arr = {1, 2, 3};
        try {
            System.out.println("before");
            arr = null;
            System.out.println(arr[100]);
            System.out.println("after");
        } catch (NullPointerException e) {
            e.printStackTrace();

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("after try catch");
    }




    public static void main4(String[] args) {
        int[] array = {1,2,3};
        try{
            System.out.println("before");
            array = null;
            System.out.println(array[100]);
            System.out.println("after");
        }catch (NullPointerException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("try - catch之后的代码");
    }
    public static void main3(String[] args) {
        int[] array = {1,2,3};
        try{
            //System.out.println(array[4]);//越界
            array = null;
            System.out.println(array.length);//空指针异常
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("访问下标越界,处理ArrayIndexOutOfBoundsException异常");
            e.printStackTrace();
        }catch (NullPointerException e){
            System.out.println("处理NullPointerException异常");

            System.out.println();
            System.out.println(e.getMessage());//只打印异常信息
            System.out.println();

            System.out.println(e);//打印异常类型

            System.out.println();

            e.printStackTrace();//打印类型和信息
        }
        System.out.println("after");
    }


    public static void main2(String[] args) {
        int[] array = new int[]{1,2,3,4};
        getindex(array,2);
    }

    public static void main1(String[] args)  {
        testException(0);
    }
}
